/**************************************************************************************************************
 * @copyright Copyright (c) 2015—2024 Uniorange Internet Design Co., LTD. All rights reserved.
 * @author Uniorange Internet Design Co., LTD.
 *
 * This file is part of the App project. Copyright © Uniorange Internet Design Co., Ltd. All Rights Reserved.
 * Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential.
 *
 **************************************************************************************************************/
package com.jinyu.core.factory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinyu.core.protocol.*;
import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 邱金波
 * @version V0.1
 * @className ProtocolFactory
 * @description 协议生成
 * @date 2024/09/19 16:33
 */
public class ProtocolFactory {
    public static Map<Integer, Class<? extends Header>> protocolMap = new HashMap<>();

    static {
        protocolMap.put(ProtocolTypeEnum.REGISTER.getType(), RegisterProtocol.class);
        protocolMap.put(ProtocolTypeEnum.PING.getType(), PingProtocol.class);
        protocolMap.put(ProtocolTypeEnum.PONG.getType(), PongProtocol.class);
        protocolMap.put(ProtocolTypeEnum.SUBSCRIBE.getType(), PongProtocol.class);
    }

    public static Header createProtocol(int type, ByteBuf body) throws IOException {
        int i = body.readableBytes();
        byte[] bytes = new byte[i];
        body.readBytes(bytes);
        ObjectMapper objectMapper = new ObjectMapper();
        Class<? extends Header> aClass = protocolMap.get(type);
        if (aClass == null)
            return null;
        return objectMapper.readValue(bytes, aClass);
    }
}
